//
//  GoodsCategory.swift
//  ReactNativeIOS
//
//  Created by FishWithoutWings on 2017/12/1.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import RealmSwift

class GoodsCategory: Object {
    
    @objc dynamic var catId = 0
    @objc dynamic var catName = ""
    @objc dynamic var parentId = 0
    @objc dynamic var enable = 0
    @objc dynamic var catCode = ""
    @objc dynamic var isType = 0
    @objc dynamic var catIndex = 0
    @objc dynamic var sort = 0
    
    override class func primaryKey() -> String? {
        return "catId"
    }

    class func create(_ goodsCategories: [Any], isAsync: Bool = true) {
        let closure = {
            let realm = YYRealm.initialize()
            
            realm.beginWrite()
            realm.delete(realm.objects(self))
            for goodsCategory in goodsCategories {
                realm.create(self, value: goodsCategory, update: true)
            }
            try! realm.commitWrite()
        }
        
        if isAsync {
            YYRealm.async(closure)
        } else {
            closure()
        }
    }
    
    class func getOne(catCode: String) -> GoodsCategory? {
        guard !catCode.isEmpty else {
            return nil
        }
        
        let realm = YYRealm.initialize()
        let items = realm.objects(self).filter("catCode = '\(catCode)'")
        if items.count > 0 {
            return items[0]
        } else {
            return nil
        }
    }
    
    class func getSubAll(catId: Int) -> [GoodsCategory] {
        let realm = YYRealm.initialize()
        let subCities = realm.objects(self).filter("parentId = \(catId)")
        return subCities.map({ (goodsCategory) -> GoodsCategory in
            return goodsCategory
        })
    }
}
